<?php
class Bootstrap
{

	/* Cette fonction configure :
	 * -la base de données
	 * -le chemin des librairies
	 * -le repertoir des modules
	 * -la racine du site
	 * -le repertoir de l'application
	 * -le repertoir des fichiers de configuration
	 */
	public function __construct($configSection = 'live')
    {
        //If you want all requests to have a session facilitated by Zend_Session, then start the session in the bootstrap file:
    	require_once 'Zend/Session.php';
    	Zend_Session::start();

    	$GLOBALS['startTime'] = microtime(true);
        $rootDir = dirname(dirname(__FILE__));/*racine du site*/


		/*Chemin des libraries */
		set_include_path(get_include_path()
            . PATH_SEPARATOR . $rootDir . '/library/'
	    );

        include 'Zend/Loader.php';
        Zend_Loader::registerAutoload();

        $defaultNamespace = new Zend_Session_Namespace('Default');

        // Load configuration
        Zend_Registry::set('configSection', $configSection);
        $config = new Zend_Config_Ini($rootDir.'/application/configuration/config.ini',
        							$configSection, array('skipExtends'=> true,	'allowModifications' => true));

		//echo "abbbb";
		if($config->flag->config->updated!="1")
		{
	     	//echo "kkkkk"; exit;

	     	//Mise à jour du fichier de configuration
			$config->path->modules->dir = $rootDir.'/application/modules';
	        $config->path->templates->dir = $rootDir.'/www/templates';
	        $config->path->root->app = $rootDir;
	        $config->path->cache->dir = $rootDir.'/var/cache';
	        $config->logFiles->error = $rootDir.'/var/log/log.txt';
	        $config->path->public->dir = $rootDir.'/www';
			$config->path->languages->dir = $rootDir.'/languages';
	        $config->flag->config->updated="1";
			// Ecrire le fichier
			$writer = new Zend_Config_Writer_Ini(array('config'   => $config,
                                          'filename' => '../application/configuration/config.ini'));		$writer->write();

		}
        Zend_Registry::set('config', $config);

        date_default_timezone_set($config->date_default_timezone);

        // configure database and store to the registery
        $db = Zend_Db::factory($config->db);
        Zend_Db_Table_Abstract::setDefaultAdapter($db);
        Zend_Registry::set('db', $db);
    }

    public function runApp()
    {
    	// setup the MVC
        Zend_Layout::startMvc();

        //get config
        $config = zend_registry::get('config');

        //print_r($config); exit(1);
        //initialisation du cache
        //bien placer l'initialisation du cache dans ce bootstrap afin
        //de pouvoir mettre en cache toute suite certaines actions:
        //langues et autres...
        $frontendOptions = array(   'lifetime' => 7200, // temps de vie du cache de 2 heures
								   'automatic_serialization' => true
								);
		$backendOptions = array(    // Répertoire où stocker les fichiers de cache
								    'cache_dir' => Zend_Registry::get('config')->path->cache->dir.'/'
								);
		$cache = Zend_Cache::factory('Output',
                             'File',
                             $frontendOptions,
                             $backendOptions);
		Zend_Registry::set('cache', $cache);
		//----------------------- fin parametrage du cache

        // acl action helper
        if($config->cache->acl->enable) {
	    	if(!$acl = $cache->load('acl')) {
	       		$acl = new Wmp_Acl_Acl();
	       		$cache->save($acl, 'acl');
	       	}
        }
        else {
        	$acl = new Wmp_Acl_Acl();
        }

        $aclHelper = new Wmp_Controller_Action_Helper_Acl(null, array('acl'=>$acl));
        Zend_Controller_Action_HelperBroker::addHelper($aclHelper);

        // setup front controller
        $frontController = Zend_Controller_Front::getInstance();
        $frontController->throwExceptions(Zend_Registry::get('config')->throwExceptions);
        $frontController->addModuleDirectory(Zend_Registry::get('config')->path->modules->dir);


        /*--------------Debut ajout des plugins---------------------------------------*/
        //Ce plugin est appelé tout au long de l'éxecution d'une action
		//=avant, pendant, après. Il sert pour tutorial
        //$frontController->registerPlugin(new Wmp_Controller_Plugin_ActionSetup());

		//Configure les chemin de view helpers, css, js
		//Dans ce plugin j'enregistre dans le registry:
        //le nom du template courant, le nom du module, le nom du controlleur et le nom
        //de l'action
        //Ce plugin doit etre enregistré avant tous les autres plugins
		$frontController->registerPlugin(new Wmp_Controller_Plugin_ViewSetup(),10);

        $frontController->registerPlugin(new Wmp_Controller_Plugin_Translations(),30);

		$frontController->registerPlugin(new Wmp_Loader_ModelAndLayout(),50);



		$errorHandler = new Zend_Controller_Plugin_ErrorHandler();
		//pour changer le module, controlleur et action de l'errorhandler
		$errorHandler->setErrorHandlerModule('error')
		       		 ->setErrorHandlerController('show')
		       		 ->setErrorHandlerAction('index');

		$frontController->registerPlugin($errorHandler);
		/************************** Fin ajout des plugins***********************************/

        // add a static route for /about
		/*Hachim : method static de reécriture d'url :
		//si on tape l'adresse.../about, ce sera l'équivalent de .../article/about
		*/
		//INFO:route je peux définir quelques routes statiques en base de données
		//voir comment gerer le multilangue avec les routes statics
		//ou automatiquement avec quelque chose du genre, ou avec un fichier de configuration
		/*
		 	$titre="titre-de-la-page"
			$route = new Zend_Controller_Router_Route_Static(
            	$titre,
            	array(	'module'=>'le module en cours',
						'controller' => 'le controller en cours',
						'action' => 'action encours',
						't'=tittre)
        	);
		 *
		 */

		//INFO : gerer les routes statics en bdd, lorsqu'on valider/enregistre
		//mettre à  jour un fichier php, que je vais lire pour les mettre ici
		//ou persister pour les manipuler from database, ici avec un foreach
		$router = $frontController->getRouter();

		// Ajout de la nouvelle route
		$router->addRoute(
		    "default",
		    new Zend_Controller_Router_Route(
		        "/:language/:module/:controller/:action/*",
		        array(
		            "language"      =>  $config->defaultLanguage,
		            "module"        =>  "default",
		            "controller"    =>  "index",
		            "action"        =>  "index"
		        )
		    )
		);

		/*$route = new Zend_Controller_Router_Route_Static(
            'home',
            array('module'=>'default', 'controller' => 'index', 'action' => 'test')
        );
        $router->addRoute('home', $route);

        $route = new Zend_Controller_Router_Route_Static(
            'error',
            array('module'=>'default', 'controller' => 'error', 'action' => 'error')
        );
        $router->addRoute('error',$route);
        */



		//Je ne dois presque pas toucher à rien
        // run!
        try {
            $frontController->dispatch();
        } catch (Exception $exception) {
        	//Tous les messages d'erreurs passent par ici
        	// an exception has occurred after the ErrorController's postdispatch() has run
            if(Zend_Registry::get('config')->debug == 1) {
            	//affiche sur le navigateur
                $msg = $exception->getMessage();
                $trace = $exception->getTraceAsString();
                echo "<div>--Error--: $msg<p><pre>$trace</pre></p></div>";
            } else {
                try {
                	//log dans le fichier des log des erreurs
                    $logFile = Zend_Registry::get('config')->logFiles->error;
                    $log = new Zend_Log(new Zend_Log_Writer_Stream($logFile));
                    $log->debug($exception->getMessage() . "\n" .  $exception->getTraceAsString() . "\n-----------------------------");
                } catch (Exception $e) {
                    // can't log it - display error message
                    die("<p>An error occurred with logging an error!");
                }
            }
        }
    }
	/**
	*/
    public function runXmlRpc()
    {
         error_reporting(0);
		/**
         * Code client :
         * $client = new Zend_XmlRpc_Client('http://localhost/Wmp_cms/www/xmlrpc');
		 * $test = $client->getProxy('test');
		 * $test->sayHello();
		 *
		 * OU
		 * try {
			print_r( $client->call('test.sayHello'));
			} catch (Zend_XmlRpc_Client_FaultException $e) {
			     print_r($e);
			     //$e->getCode();
			     //$e->getMessage();
			}
		 *
         */
    	$config = Zend_Registry::get('config');


        $writer = new Zend_Log_Writer_Stream($config->path->root->app . '/var/log/xmlrpc.log');
        $logger = new Zend_Log($writer);

        Zend_XmlRpc_Server_Fault::attachFaultException('Exception');

    	$cacheFile = $config->path->public->dir. '/xmlrpc/xmlrpc.cache';
		$server = new Zend_XmlRpc_Server();

		if (!Zend_XmlRpc_Server_Cache::get($cacheFile, $server)) {
		    $server->setClass('Wmp_Service_Test_Test', 'test');   // test. namespace
		    Zend_XmlRpc_Server_Cache::save($cacheFile, $server);
		}
        $response = $server->handle();
        $logger->info($server->getRequest()->getFullRequest());
        $response->setEncoding($config->charset);
        header('Content-Type: text/xml; charset=' . $config->charset);
        echo $response;
    }

    /**
     * Enter description here...
     *
     */
    public function runRest()
    {
    	$config = Zend_Registry::get('config');
    	$server = new Zend_Rest_Server();
    	$server->setClass('Wmp_Service_Test_Test','test');
		$server->handle();
    }
    
    public function runAmf()
    {
    	ini_set('display_errors','1');
		ini_set('display_startup_errors','1');
		error_reporting (E_ALL);
		
		//Instantiate server
		$server = new Zend_Amf_Server();
		$server->setClass('Wmp_Service_Wmp_CodeGenerator_Form','GeneratorForm');
		$server->setClassMap('MyObject','Wmp_Service_Wmp_CodeGenerator_MapContact');
		echo ($server->handle());
    }
}